import {messages, queryCurrencyPrecision} from "share/common";
import React from 'react'
import { Form, Button, Table, Row, Col, Select,Tag, message, Icon, Input, Popconfirm, Checkbox } from 'antd'
import config from 'config'
import moment from 'moment'
import FileSaver from 'file-saver';
import batchPrintService from 'containers/financial-management/batch-print.service';
import errorMessage from "share/errorMessage";
//特定角色选择部门
import {SelectDepByRole} from 'components/index';
import ResizeTable from 'components/resize-table'
import SearchArea from 'components/search-area'
import 'styles/financial-management/batch-print-invoice.scss'

class BatchPrintView extends React.Component{
  constructor(props) {
    super(props);
    this.bathGenerationCompletion=false;

    this.state = {
      hasBorn: false, //是否生成
      loading: false,
      downFailLoading: false, //下载fail数据
      exportLoading: false,
      buttonLoading: false,
      keyword: null,
      countSelect: localStorage.getItem('batchEachCount')||-1,
      selectedData: [],
      countList: [
        {
          title: messages('financial-management.key1'/*全部*/),//'全部',
          value: -1   //-1表示全部
        },
        {title: 500, value: 500},
        {title: 1000, value: 1000},
        {title: 1500, value: 1500},
        {title: 2000, value: 2000}
      ],
      searchForm: [
        {
          type: 'multiple',
          id: 'legalEntity',
          label: messages('financial-management.key2'/*法人实体*/), //法人实体
          options: [],
          getUrl: `${config.baseUrl}/api/finance/role/corporations`,
          method: 'get',
          labelKey: 'companyName',
          valueKey: 'companyReceiptedOID',
          enableKey: 'enabled',
          renderOption: option => (`${option.companyName}${(option.enabled ? '' : '(已禁用)')}`)
        },
        { type: 'radio',
          label: messages('financial-management.key3'/*审核通过日期*/),
          id: 'dateOption',
          event: 'DATE_RANGE',
          defaultValue: 0,
          options: [{label: messages('financial-management.key1'/*全部*/), value: 0},
          {label: messages('financial-management.key4'/*当月*/), value: 1},
          {label: messages('financial-management.key5'/*上月*/), value: 2}]
        },
        {type: 'datePicker', id: 'dateFrom', label: messages('financial-management.key3'/*审核通过日期*/)} //审核通过日期
      ],
      searchParams: {
        corporationOIDs: [],
        departmentOIDs: [],
        startDate: '',
        endDate: ''
      },
      columns: [
        {title: messages('financial-management.key6'/*批次号*/), dataIndex: 'batchNumber'}, //批次号
        {title: messages('financial-management.key7'/*电子票数*/), dataIndex: 'invoiceCount'}, //电子票数
        {title: messages('financial-management.key8'/*创建人工号*/), dataIndex: 'employeeId'}, //创建人工号
        {title: messages('financial-management.key9'/*创建人姓名*/), dataIndex: 'createdName'}, //创建人姓名
        {title: messages('financial-management.key10'/*操作*/), dataIndex: 'operation', width:'25%',render: (text, record, index) => (  //操作
          <span>
            {
              this.checkPageRoleForOld('PRINTINVOICEBATCH', 2) &&
              record.pdfStatus===1 &&
              <a onClick={(e) => this.printItem(e, record,index)}>{messages('financial-management.key11'/*打印*/)}</a>
            }{/*打印*/}
            {
              this.checkBatchGenerationCompletion(record) &&
              <Icon type="loading" />
            }
            {
              this.checkPageRoleForOld('PRINTINVOICEBATCH', 2) &&
              (record.pdfStatus===3 || record.pdfStatus===0) &&
              <sapn>失败</sapn>
            }{/*失败*/}
            <span className="ant-divider" />
            <a onClick={(e) => this.downloadReport(e, record,index)}>{messages('financial-management.key12'/*下载批次报表*/)}</a>
            {/*下载批次报表*/}
            <span className="ant-divider" />
            {/*删除后该批次的电子发票将回到待打印电子票中？*/}
            {
              this.checkPageRoleForOld('PRINTINVOICEBATCH', 2) &&
              <Popconfirm title={messages('financial-management.key13'/*删除后该批次的电子发票将回到待打印电子票中？*/)}
                          onConfirm={(e) => this.deleteItem(e, record,index)}><a>{messages('financial-management.key14'/*删除*/)}</a></Popconfirm>
            }
            {/*删除*/}
          </span>)},
        // 已完成打印
        {title: messages('financial-management.key15'/*已完成打印*/), dataIndex: 'printSuccess', width: '10%',render: (text, record, index) => (
          <span>
            {
              this.checkPageRoleForOld('PRINTINVOICEBATCH', 2) &&
              <Checkbox
                onChange={(e) => this.printSuccess(e, record, index)}
                checked={record.printSuccess}
              />
            }
          </span>
        )},
      ],
      extraDep: {
        res: [],
        title: <span className={'placeholder-class'}>{messages('financial-management.key16'/*请选择*/)}</span>,//"请选择",
        depClassName: "f-right select-dep-close-wrap",
        className: ["placeholder-class f-right select-dep-close-wrap", "f-right select-dep-close-wrap select-dep-close-wrap-show"]
      },
      failData: {},
      batchData: {},
      depModalShow: false,
      data: [],
      pagination: {
        total: 0
      },
      pageSize: 10,
      page: 0
    }
  }

  componentWillMount() {
    //获取批次总数
    this.getBatch();
    //获取失败的批次数据
    this.getFailedBatch();
    //获取列表
    this.getList(0);
  }

  //检查生成批次是否异步处理完成
  checkBatchGenerationCompletion=(record)=>{
    let completion=(record.pdfStatus===2);
    if(completion&&this.bathGenerationCompletion)
    {
      this.bathGenerationCompletion=false;
      setTimeout(()=>{
        this.getFailedBatch();
        this.getList(0);
      },1500);
    }
    return completion;
  }
  //修改打印状态
  printSuccess(e, record, index){
    batchPrintService.changePrintStatus(record.id, !record.printSuccess).then(res => {
      if(res.data && res.data.success){
        record.printSuccess = res.data.rows.printSuccess;
        let data = this.state.data;
        data.rows[index] = record;
        this.setState({
          data: data
        })
      }
    }).catch((e) => {
      errorMessage(e.response);
    });
  }

  //打印
  printItem(e, record, index){
    e.stopPropagation();
    batchPrintService.printItem(record.id).then(res => {
      if(res.data){
        let winRef = window.open(res.data.rows.fileURL, "_blank");
      }
    }).catch((e) => {

    });
  };
  //下载
  downloadReport(e, record, index){
    e.stopPropagation();
    batchPrintService.downloadReport(record.id).then(res => {
      if(res.data){
        let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        let name = record.batchNumber +'-'+messages('financial-management.key17'/*电子发票打印*/);  //电子发票打印
        FileSaver.saveAs(b, `${name}.xlsx`);
        message.success(messages('financial-management.key18'/*下载成功*/)); //下载成功
      }
    }).catch((e) => {
      errorMessage(e.response, messages('financial-management.key19'/*下载失败*/));
    });
  };
  //删除
  deleteItem(e, record, index){
    batchPrintService.delete(record.id).then(res => {
      if(res.data.success){
        let array = this.state.data.rows;
        array.splice(index, 1);
        this.getBatch();
        let params = {
          businessCode: this.state.keyword,
          page: (this.state.page + 1) * this.state.pageSize - 1,
          size: 1
        };
        batchPrintService.getList(params).then((res) => {
          if (res.data.success) {
            this.setState({
              pagination: {
                total: res.data.total
              }
            });
            if(res.data.rows.length > 0){
              array.push(res.data.rows[0]);
            }
            this.setState({
              data: {
                rows: array
              }
            })
          }
        })
      }
    }).catch((e) => {
      errorMessage(e.response, messages('financial-management.key20'/*删除失败*/));
    });
  };

  getFailedBatch(){
    batchPrintService.getFailedBatch().then((res) => {
      if (res.status === 200 && res.data && res.data.success) {
        this.setState({
          failData: res.data.rows,
        })
      }
    }).catch((e) => {
      errorMessage(e.response);
    });
  }

  getBatch() {
    this.setState({buttonLoading:true});
    let params = this.state.searchParams;
    let {batchData}=this.state;
    batchPrintService.getBatch(params).then((res) => {
      if (res.status === 200 && res.data && res.data.success) {
        if(batchData.batchCount)
        res.data.rows.batchCount=batchData.batchCount;
        this.setState({
          batchData: res.data.rows,
        })
      }
      this.setState({buttonLoading:false})
    }).catch((e) => {
      errorMessage(e.response);
    })
  }

  search = (result) => {
    let {searchParams}=this.state;
    searchParams.corporationOIDs=result.legalEntity ? result.legalEntity :[];
    searchParams.startDate='';
    searchParams.endDate='';
    let startDate =moment(moment().format('YYYY-MM-DD'), 'YYYY-MM-DD');
    let endDate = moment(moment().format('YYYY-MM-DD'), 'YYYY-MM-DD');

    if(result.dateOption===1){
      startDate = startDate.startOf('month')._d;
      endDate = endDate.endOf('day')._d;
    }
    if(result.dateOption===2){
      startDate = startDate.subtract(1, 'month').startOf('month')._d;
      endDate = endDate.subtract(1, 'month').endOf('month')._d;
    }
    if(result.dateFrom && result.dateFrom.length > 0){
      searchParams.startDate = new Date(result.dateFrom[0]._d).format('yyyy-MM-dd') + 'T' + '00:00:00' + 'Z';
      searchParams.endDate = new Date(result.dateFrom[1]._d).format('yyyy-MM-dd') + 'T' + '23:59:59' + 'Z';
      if(result.dateOption!=0) {
        if(new Date(startDate)>new Date(result.dateFrom[0]._d)) {
          searchParams.startDate=new Date(startDate).format('yyyy-MM-dd') + 'T' + '00:00:00' + 'Z';
        }
        if(new Date(endDate)<new Date(result.dateFrom[1]._d)) {
          searchParams.endDate = new Date(endDate).format('yyyy-MM-dd') + 'T' + '23:59:59' + 'Z';
        }
      }
    }
    else{
      if(result.dateOption!=0) {
          searchParams.startDate=new Date(startDate).format('yyyy-MM-dd') + 'T' + '00:00:00' + 'Z';
          searchParams.endDate = new Date(endDate).format('yyyy-MM-dd') + 'T' + '23:59:59' + 'Z';
      }
    }
    this.setState({
      searchParams:searchParams
    }, ()=>{
      this.getBatch();
    })
  };
  //下载failed数据
  downloadFail = () => {
    this.setState({ downFailLoading: true });
    batchPrintService.downloadFail().then(res => {
      this.setState({ downFailLoading: false });
      if(res.data){
        let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        let name = messages('financial-management.key21'/*生成批次失败的电子票*/); //失败的电子票数据
        FileSaver.saveAs(b, `${name}.xlsx`);
        message.success(messages('financial-management.key18'/*下载成功*/)); //下载成功
      }
    }).catch((e) => {
      this.setState({ downFailLoading: false });
      errorMessage(e.response, messages('financial-management.key20'/*删除失败*/));
    });
  };

  clear = () => {
    let searchParams = {
      corporationOIDs: [],
      departmentOIDs: [],
      startDate: '',
      endDate: ''
    };
    this.depConfirmCallBack([]);
    this.setState({ searchParams: searchParams })
  };
  //清空 keyword
  emitEmpty = () => {
    this.setState({ keyword: '' });
    this.getList(0);
  };

  //根据businessCode 搜索
  onChangeKeyword = (e) => {
    this.setState({ keyword: e.target.value },()=>{
      this.getList(0);
    });
  };

  getList = (page) => {
    let params = {
      businessCode: this.state.keyword,
      page: page,
      size: this.state.pageSize
    };
    this.setState({
      page: page
    });
    batchPrintService.getList(params).then((res) => {
      if (res.status === 200) {
        this.bathGenerationCompletion=true;
        this.setState({
          pagination: {
            total: res.data.total
          },
          data: res.data
        })
      }
    }).catch((e) => {
      errorMessage(e.response);
    });
  };

  //下拉选择框
  countChange = (value) => {
    this.setState({
      countSelect: value
    })
  };
  //分页点击
  onChangePager = (pagination,filters, sorter) =>{
      this.getList(pagination.current-1);
  };

  //打开部门树
  openDepModal=()=>{
    this.setState({depModalShow:true});
  }
  //部门树回调
  depConfirmCallBack =(res)=>{
    this.setState({depModalShow:false});
    let extraDep = this.state.extraDep;
    let searchParams = this.state.searchParams;
    let deps = [];
    extraDep.res = res;
    if (extraDep.res.length > 0) {
      extraDep.depClassName = extraDep.className[1];
    } else {
      extraDep.depClassName = extraDep.className[0];
    }
    for (let i = 0; i < extraDep.res.length; i++) {
      deps.push(extraDep.res[i].departmentOID);
    }
    searchParams.departmentOIDs = deps;
    extraDep.title = this.renderButtonTitle(extraDep.res);
    this.setState({
      extraDep,
      searchParams
    })
  }
  onMouseLeaveDepTag = (e) => {
    e.stopPropagation();

  };
  onMouseEnterDepTag = (e) => {
    e.stopPropagation();

  };
  //清除已经选择的部门
  onClearDepTag = (e) => {
    e.stopPropagation();
    this.depConfirmCallBack([]);
  };
  depCancelCallBack=()=>{
    this.setState({depModalShow:false})
  }
  //渲染已经选择的部门
  renderButtonTitle(titleArr) {
    if (titleArr.length < 1) {
      // 请选择
      return <span className={'placeholder-class'}>{messages('financial-management.key16'/*请选择*/)}</span>;
    }
    let node = [];
    titleArr.map((item, i) => {
      node.push(<Tag key={i}>{item.name}</Tag>);
    })
    return node;
  }

  //导出事件
  handleExport = () => {
    let params = this.state.searchParams;
    const { batchData } = this.state;

    params.invoiceCount = this.state.batchData.invoiceCount;
    params.totalAmount = this.state.batchData.totalAmount;
    params.eachCount = this.state.countSelect;
    this.setState({ exportLoading: true });
    localStorage.setItem('batchEachCount',params.eachCount)
    batchPrintService.export(params).then(res => {
      this.setState({ exportLoading: false });
      this.setState({
        hasBorn: true
      });
      if(res.data && res.data.success){
        this.getList(0);
        this.setState({
          batchData: res.data.rows
        },()=>{
          this.getBatch();
        })
        message.success(messages('financial-management.key22'/*生成批次成功*/));
      }
      else if(res.data && res.data.code === 'E_INVOICE_001'){
        this.getFailedBatch();
        this.setState({
          batchData: res.data.rows
        },()=>{
          Modal.confirm({
            title: '提示',
            content: '发票金额和数量有变动，请重新确认',
            okText: '确定',
            cancelText: '取消',
            onOk: ()=>{
             this.handleExport();
            }
          });
        })
      }
      else{
        this.getFailedBatch();
        errorMessage(res.data.message);
      }
    }).catch((e) => {
      this.getBatch();
      this.getFailedBatch();
      this.setState({ exportLoading: false });
      errorMessage(e.response);
    });
  };

  render() {

    const { depModalShow,loading, exportLoading, searchForm, checkboxListForm, columns, data, pagination, countList, batchData, failData, downFailLoading, keyword, countSelect, hasBorn, buttonLoading } = this.state;
    let failMessage, bornTip, invoiceCount, totalAmount;
    //失败提示
    if(failData.invoiceCount && failData.invoiceCount > 0){
      failMessage = <div className="fail-tip">
        <Row type="flex" justify="space-between">
          <Col span={18}>
            <Icon type="info-circle" />
            {/*当前有*/}
            {/*笔发票生成批次失败，价税合计*/}
            {`${messages('financial-management.key23'/*当前有*/)} ${failData.invoiceCount || 0} ${messages('financial-management.key24'/*笔发票生成批次失败，价税合计*/)}`}<span>CNY {this.filterMoney(failData.totalAmount/100,queryCurrencyPrecision('CNY'))}</span>
          </Col>
          <Col span={6} className="text-right">
            <Button type="dashed" onClick={this.downloadFail} loading={downFailLoading}
                    icon="download" size="small">
              {/*下载查看*/}
              {messages('financial-management.key25'/*下载查看*/)}
            </Button>

          </Col>
        </Row>
      </div>
    } else {
      failMessage = '';
    }
    //生成批次提示
    if(hasBorn){
      bornTip = <div>
        {messages('financial-management.key26'/*操作成功，共生成*/)}
        {/*操作成功，共生成*/}
        <span className="green-text">{batchData.batchCount}</span>
        {messages('financial-management.key27'/*个批次，请及时打印*/)}
        {/*个批次，请及时打印*/}
      </div>
    } else {
      bornTip = <div>{messages('financial-management.key28'/*当批次中数量过大可能导致打印失败，请根据您的机器性能进行选择，推荐：500条/批*/)}</div>;
      // 当批次中数量过大可能导致打印失败，请根据您的机器性能进行选择，推荐：500条/批
    }

    //电子票数量

    invoiceCount = `<span class="green-text">${batchData.invoiceCount || 0} </span>`;
    totalAmount = `<span class="green-text">CNY ${this.filterMoney(batchData.totalAmount/100,queryCurrencyPrecision('CNY'),true)}</span>`;

    const clear = keyword ? <Icon type="close-circle" onClick={this.emitEmpty} /> : null;
    const html = {
      __html: messages('financial-management.key543',{arg1:invoiceCount,arg2:totalAmount}/*待打印电子票:共计{arg1}笔，价税合计{arg2}*/)
    };
    const htmll = {
      __html: messages('financial-management.key29'/**只可打印通过<span class=*/)
    };
    return (
      <div className="batch-print-invoice">
        {failMessage}
        <SearchArea
          extraFields={
            [
              <div>
                <div className="select-dep-search-area-title">
                  {/*部门:*/}
                  {messages('financial-management.key30'/*部门*/) + ":"}
                </div>
                <div className="select-dep-search-area" onClick={this.openDepModal}>
                  <div className="f-left select-dep-wrap">
                    {this.state.extraDep.title}
                  </div>
                  <div
                    className={this.state.extraDep.depClassName}
                    onMouseLeave={this.onMouseLeaveDepTag}
                    onMouseEnter={this.onMouseEnterDepTag}
                    onClick={this.onClearDepTag}
                  >
                    <Icon type="close-circle" className="closeCircle"/>
                  </div>
                </div>
              </div>
            ]
          }
          searchForm={searchForm}
          submitHandle={this.search}
          clearHandle={this.clear}
        />
        <div className="print-message">
          {exportLoading && <Icon type="loading" /> ||<div className="total-title" dangerouslySetInnerHTML={html}/>}
          <Row>
            <Col>
              <div className="import-invoice">
                {/*设置打印批次*/}
                {messages('financial-management.key31'/*设置打印批次*/)}：
                <Select
                  defaultValue={ (countSelect!=-1&&countSelect) ||messages('financial-management.key1'/*全部*/)}
                  onChange={this.countChange}
                  filterOption={false}
                >
                  {/*全部*/}
                  {countList.map(d => <Option key={d.value}>{d.title}</Option>)}
                </Select>
                <span className="unit">/
                  {messages('financial-management.key32'/*批*/)}
                  {/*批*/}
                  </span>
                {
                  this.checkPageRoleForOld('PRINTINVOICEBATCH', 2) &&
                  <Button
                    type="primary"
                    onClick={this.handleExport}
                    loading={exportLoading ||buttonLoading}
                    disabled={batchData.invoiceCount == 0}
                  >
                    {messages('financial-management.key33'/*生成批次*/)}
                    {/*生成批次*/}
                  </Button>
                }
              </div>
            </Col>
          </Row>
          <div className="table-header-title">
            {bornTip}
          </div>
          <div className="table-header-title" dangerouslySetInnerHTML={htmll} />
        </div>
        <div className="background-transparent">
          <div style={{backgroundColor:"#ffffff",margin:"0 -20px",padding:"20px"}}>
            <div className="table-search" >
              <Row>
                <Col span={18} className="list-title">
                  {messages('financial-management.key34'/*打印批次列表*/)}
                  {/*打印批次列表*/}
                </Col>
                <Col span={6} className="text-right">
                  {/*请输入单据号*/}
                  <Input
                    placeholder={messages('financial-management.key35'/*请输入单据号*/)}
                    suffix={<Icon type="search" className='font-disabled'/>}
                    value={keyword}
                    onChange={this.onChangeKeyword}
                  />
                </Col>
              </Row>
            </div>
            <ResizeTable
              rowKey={record => record.batchNumber}
              columns={columns}
              dataSource={data.rows}
              loading={loading}
              pagination={pagination}
              onChange={this.onChangePager}
              bordered
              size="middle"
            />
          </div>
        </div>
        <SelectDepByRole
          multiple
          isShow={depModalShow}
          title="选择部门"
          apiServiceKey={"getFinanceRoleTree"}
          onCancel={this.depCancelCallBack}
          onConfirm={this.depConfirmCallBack}
        />
      </div>
    )
  }
}

const WrappedUploadFile1= Form.create()(BatchPrintView);

export default WrappedUploadFile1;

